package handlers

import (
	"net/http"

	"github.com/ev-charging/cloud-platform/internal/device"
	"github.com/gin-gonic/gin"
)

// DeviceHandler 设备API处理器
type DeviceHandler struct {
	deviceService *device.Service
}

// NewDeviceHandler 创建设备API处理器
func NewDeviceHandler(deviceService *device.Service) *DeviceHandler {
	return &DeviceHandler{
		deviceService: deviceService,
	}
}

// ListDevices 获取所有设备列表
func (h *DeviceHandler) ListDevices(c *gin.Context) {
	devices := h.deviceService.ListDevices()
	c.JSON(http.StatusOK, gin.H{"data": devices, "count": len(devices)})
}

// GetDevice 获取单个设备信息
func (h *DeviceHandler) GetDevice(c *gin.Context) {
	deviceID := c.Param("id")
	device, exists := h.deviceService.GetDevice(deviceID)
	if !exists {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": device})
}

// GetDeviceStatus 获取设备状态
func (h *DeviceHandler) GetDeviceStatus(c *gin.Context) {
	deviceID := c.Param("id")
	device, exists := h.deviceService.GetDevice(deviceID)
	if !exists {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"device_id": device.ID, "status": device.Status, "last_active": device.LastActive})
}

// SendCommand 发送命令到设备
func (h *DeviceHandler) SendCommand(c *gin.Context) {
	deviceID := c.Param("id")

	var command map[string]interface{}
	if err := c.ShouldBindJSON(&command); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的命令格式"})
		return
	}

	// 检查设备是否存在
	_, exists := h.deviceService.GetDevice(deviceID)
	if !exists {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	// 发送命令
	if err := h.deviceService.SendCommand(deviceID, command); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送命令失败: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "命令已发送"})
}

// GetDeviceCount 获取设备总数
func (h *DeviceHandler) GetDeviceCount(c *gin.Context) {
	devices := h.deviceService.ListDevices()
	c.JSON(http.StatusOK, gin.H{"count": len(devices)})
}

// GetActiveDevicesCount 获取活跃设备数量
func (h *DeviceHandler) GetActiveDevicesCount(c *gin.Context) {
	devices := h.deviceService.ListDevices()
	activeCount := 0

	for _, d := range devices {
		if d.Status == "online" || d.Status == "charging" {
			activeCount++
		}
	}

	c.JSON(http.StatusOK, gin.H{"active_count": activeCount, "total_count": len(devices)})
}
